package com.itheima.easy.security;

import com.alibaba.fastjson.JSONObject;
import com.itheima.easy.base.AjaxResult;
import com.itheima.easy.enums.BasicEnum;
import com.itheima.easy.utils.AjaxResultBuild;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName RestAuthoricationEntryPoint.java
 * @description 用户在未登录状态下直接请求需要登录的接口，应该报401
 */
@Component
public class RestAuthoricationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        PrintWriter out = response.getWriter();
        AjaxResult<Boolean> responseWrap = AjaxResultBuild.build(BasicEnum.SECURITY_ACCESSDENIED_FAIL, false);
        out.write(JSONObject.toJSONString(responseWrap));
        out.flush();
        out.close();
    }
}

